package com.example.objectPool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

// 对象池的每一个元素类型
public class DataConnection {
    private String connectionId;

    public DataConnection(String connectionId) {
        this.connectionId = connectionId;
    }

    public void executeQuery(String query) {
        System.out.println("Executing query: " + query + "ConnectinId: " + connectionId);
    }

    public void close() {
        System.out.println("Closing connection: " + connectionId);
    }
}

class DataConnectionPool {
    // 线程安全的队列
    private BlockingQueue<DataConnection> pool;

    private int maxPoolSize;

    public DataConnectionPool(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    /**
     * 初始化连接
     */
    public void intializePool() {
        pool = new LinkedBlockingQueue<>();

        for (int i = 0; i < maxPoolSize; i++) {
            pool.offer(new DataConnection("ConnectionId:" + i));
        }
    }

    /**
     * 获取连接
     * @return
     * @throws InterruptedException
     */
    public DataConnection getConnection() throws InterruptedException {
        if (pool.size() > 0) {
            return pool.take();
        }
        return null;
    }

    /**
     * 将连接放回对象池
     * @param connection
     */
    public void releaseConnection(DataConnection connection) {
        if (connection != null) {
            pool.offer(connection);
        }
    }
}